package com.yunxin.admin.system.api.core.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunxin.admin.system.domain.model.user.UserMerchantRepository;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.common.constant.SystemConstants;
import com.yunxin.admin.system.infra.framework.resubmit.Resubmit;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.admin.system.infra.persistence.mapper.SysUserMerchantMapper;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.core.application.dto.order.OrderUserApplyDetailDTO;
import com.yunxin.core.application.service.TeamService;
import com.yunxin.core.customer.domain.CustomInfoAuthorizationLog;
import com.yunxin.core.customer.domain.CustomerOperationLog;
import com.yunxin.core.customer.dto.*;
import com.yunxin.core.customer.service.CustomerInfoService;
import com.yunxin.core.customer.service.RiskManagementService;
import com.yunxin.core.customer.vo.*;
import com.yunxin.core.domain.model.team.Team;
import com.yunxin.core.domain.model.team.UserTeamShip;
import com.yunxin.core.infra.persistence.mapper.user.UserTeamShipMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zero°
 * @since 2023-06-08
 */
@Tag(name = "11.客户管理")
@Slf4j
@RestController
@RequestMapping("/core/v1/customer")
@RequiredArgsConstructor
public class CustomerController {

    @Autowired
    private CustomerInfoService customerInfoService;

    private final TeamService teamService;

    private final UserMerchantRepository userMerchantRepository;

    private final SysUserMerchantMapper sysUserMerchantMapper;

    private final UserTeamShipMapper userTeamShipMapper;

    @Autowired
    private RiskManagementService riskManagementService;

    @Operation(summary = "根据客户检测风控信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/examineRiskManagement")
    public Result examineRiskManagement(@Validated @RequestBody RiskGetDTO riskGetDTO) {
        Long userId = SecurityUtils.X.getUser().getUserId();
        riskGetDTO.setCreateUserId(userId);
        Long logId = riskManagementService.examineRiskManagement(riskGetDTO);
        return Result.success(logId);
    }

    @Operation(summary = "用户检测风控信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/examineRiskByUser")
    public Result examineRiskByUser(@Validated @RequestBody RiskGetByUserDTO riskGetByUserDTO) {
        Long userId = SecurityUtils.X.getUser().getUserId();
        riskGetByUserDTO.setCreateUserId(userId);
        Long logId = riskManagementService.examineRiskManagement(riskGetByUserDTO);
        return Result.success(logId);
    }

    @Operation(summary = "根据企微用户id获取风控信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/getRiskManagement")
    public Result<List<CustomInfoAuthorizationLog>> getRiskManagement(@RequestParam(value = "wechatCustomerId")Long wechatCustomerId) {
        List<CustomInfoAuthorizationLog> logs = riskManagementService.getRiskManagement(wechatCustomerId);
        return Result.success(logs);
    }

    @Operation(summary = "分页获取风控信息人员列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/getRiskManagementPage")
    public Result<Page<CustomInfoAuthorizationLog>> getRiskManagementPage(@Validated @RequestBody RiskGetByUserPageDTO riskGetByUserPageDTO) {
        List<Long> list = new ArrayList<>();
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            if (SecurityUtils.X.isBokeMerchantUser()) {
                list.addAll(sysUserMerchantMapper.getUserListByMerchantId(merchantId,SecurityUtils.X.getRoleCodeList(),riskGetByUserPageDTO.getTeamId()));
            }else if (SecurityUtils.X.isBokeTeamUser()){
                List<Integer> teamIds = new ArrayList<>();
                if (ObjectUtils.isEmpty(riskGetByUserPageDTO.getTeamId())){
                    teamIds = teamService.getTeamListByUserId(userId).stream().map(Team::getId).toList();
                }else {
                    teamIds.add(riskGetByUserPageDTO.getTeamId());
                }
                list.addAll(userTeamShipMapper.selectList(new LambdaQueryWrapper<UserTeamShip>().in(UserTeamShip::getTeamId, teamIds)).stream().map(UserTeamShip::getUserMerchantId).toList());
            }else {
                list.add(userId);
            }
        }else {
            list.addAll(sysUserMerchantMapper.getUserListByMerchantId(riskGetByUserPageDTO.getMerchantId(),SecurityUtils.X.getRoleCodeList(),riskGetByUserPageDTO.getTeamId()));
//            if (!ObjectUtils.isEmpty(riskGetByUserPageDTO.getMerchantId())){
//
//            }else if (!ObjectUtils.isEmpty(riskGetByUserPageDTO.getTeamId())){
//                List<Integer> teamIds = new ArrayList<>();
//                teamIds.add(riskGetByUserPageDTO.getTeamId());
//                list.addAll(userTeamShipMapper.selectList(new LambdaQueryWrapper<UserTeamShip>().in(UserTeamShip::getTeamId, teamIds)).stream().map(UserTeamShip::getUserMerchantId).toList());
//            }
        }
        if (list.size()==0){
            return Result.success(null);
        }
        riskGetByUserPageDTO.setCreateUserIdList(list);
        Page<CustomInfoAuthorizationLog> riskManagementPage = riskManagementService.getRiskManagementPage(riskGetByUserPageDTO);
        return Result.success(riskManagementPage);
    }


    @Operation(summary = "根据id获取风控信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/getRiskManagementById")
    public Result<List<CustomInfoAuthorizationLog>> getRiskManagementById(@RequestParam(value = "id")Long id) {
        CustomInfoAuthorizationLog customInfoAuthorizationLog = riskManagementService.getRiskManagementById(id);
        List<CustomInfoAuthorizationLog> logs = new ArrayList<>();
        logs.add(customInfoAuthorizationLog);
        return Result.success(logs);
    }

    @Operation(summary = "分页查询客户列表(公海池)-管理员", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/customerSeasPageQuery")
    public PageResult<CustomerInfoVo> customerSeasPageQuery(@Validated @RequestBody CustomerPageDto command) {
        // 每个商户管理员只能看自己商户的数据
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            if (!SecurityUtils.X.isBokeMerchantUser()&&!SecurityUtils.X.isBokeTeamUser()) {
                throw new BusinessException("您不是商户管理员或团队管理员");
            }
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            command.setMerchantId(merchantId);
            if (ObjectUtils.isEmpty(command.getTeamIds())){
                if (!SecurityUtils.X.isBokeMerchantUser()){ //团队管理员
                    List<Team> teamListByUserId = userTeamShipMapper.getTeamListByUserId(userId);
                    List<Integer> teamIds = teamListByUserId.stream().map(Team::getId).toList();
                    command.setTeamIds(teamIds);
                }
            }
        }
        command.setSeasType(1);
        IPage<CustomerInfoVo> customerInfoPage = customerInfoService.customerPageQuery(command);
        return PageResult.success(customerInfoPage.getRecords(), customerInfoPage.getTotal());
    }

    @Operation(summary = "分页查询客户列表-管理员", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/customerPageQuery")
    public PageResult<CustomerInfoVo> customerPageQuery(@Validated @RequestBody CustomerPageDto command) {
        // 每个商户管理员只能看自己商户的数据
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            if (!SecurityUtils.X.isBokeMerchantUser()&&!SecurityUtils.X.isBokeTeamUser()) {
                throw new BusinessException("您不是商户管理员或团队管理员");
            }
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            command.setMerchantId(merchantId);
            if (ObjectUtils.isEmpty(command.getTeamIds())){
                if (!SecurityUtils.X.isBokeMerchantUser()){ //团队管理员
                    List<Team> teamListByUserId = userTeamShipMapper.getTeamListByUserId(userId);
                    List<Integer> teamIds = teamListByUserId.stream().map(Team::getId).toList();
                    command.setTeamIds(teamIds);
                }
            }
        }
        IPage<CustomerInfoVo> customerInfoPage = customerInfoService.customerPageQuery(command);
        return PageResult.success(customerInfoPage.getRecords(), customerInfoPage.getTotal());
    }

    @Operation(summary = "分页查询话务客户列表-话务员", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/customerTelephonerPageQuery")
    public PageResult<CustomerTelephoneInfoVo> customerTelephonerPageQuery(@Validated @RequestBody CustomerTelephonerPageDto command) {
        Long userId = SecurityUtils.X.getUser().getUserId();
        if (!SecurityUtils.X.isRoot()){
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            command.setMerchantId(merchantId);
            if (!SecurityUtils.X.isBokeMerchantUser()){
                if (SecurityUtils.X.isBokeTeamUser()){
                    if (ObjectUtils.isEmpty(command.getTeamIds())){
                        List<Integer> teamIds = teamService.getTeamListByUserId(userId).stream().map(Team::getId).toList();
                        command.setTeamIds(teamIds);
                    }
                }else {
                    command.setTelephonerId(userId);
                }
            }
        }
        //查询话务员数据
        command.setUserType(1);
        // 每个话务员只能自己的数据
        command.setSeasType(0); //非公海池数据
        IPage<CustomerTelephoneInfoVo> customerInfoPage = customerInfoService.customerTelephonerPageQuery(command);
        return PageResult.success(customerInfoPage.getRecords(), customerInfoPage.getTotal());
    }

//    @Operation(summary = "分页查询业务客户列表-业务员", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/customerSalesmanPageQuery")
//    public PageResult<CustomerSalesmanInfoVo> customerSalesmanPageQuery(@Validated @RequestBody CustomerSalesmanPageDto command) {
//        if (!SecurityUtils.X.isSalesmanUser()) {
//            throw new BusinessException("您不是业务员");
//        }
//        // 每个业务员只能自己的数据
//        Long userId = SecurityUtils.X.getUser().getUserId();
//        command.setSalesmanId(userId);
//        IPage<CustomerSalesmanInfoVo> customerInfoPage = customerInfoService.customerSalesmanPageQuery(command);
//        return PageResult.success(customerInfoPage.getRecords(), customerInfoPage.getTotal());
//    }

    @Operation(summary = "分页查询企微客户列表(已添加)", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/customerWechatPageQuery")
    public PageResult<CustomerWechatInfoVo> customerWechatPageQuery(@Validated @RequestBody CustomerWechatPageDto command) {
        command.setIsSalesmanUser(false);
        List<Long> list = new ArrayList<>();
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            if (SecurityUtils.X.isBokeMerchantUser()) {
                //command.setMerchantId(merchantId);
                list.addAll(sysUserMerchantMapper.getUserListByMerchantId(merchantId,SecurityUtils.X.getRoleCodeList(),command.getTeamId()));
            }else if (SecurityUtils.X.isBokeTeamUser()){
                List<Integer> teamIds = new ArrayList<>();
                if (ObjectUtils.isEmpty(command.getTeamId())){
                    teamIds = teamService.getTeamListByUserId(userId).stream().map(Team::getId).toList();
                }else {
                    teamIds.add(command.getTeamId());
                }
                list.addAll(userTeamShipMapper.selectList(new LambdaQueryWrapper<UserTeamShip>().in(UserTeamShip::getTeamId, teamIds)).stream().map(UserTeamShip::getUserMerchantId).toList());
            }else {
                list.add(userId);
                command.setIsSalesmanUser(true);
            }
            if (list.size()==0){
                return PageResult.success(null,0);
            }

        }else {
            list.addAll(sysUserMerchantMapper.getUserListByMerchantId(command.getMerchantId(),SecurityUtils.X.getRoleCodeList(),command.getTeamId()));
//            if (!ObjectUtils.isEmpty(command.getMerchantId())){
//
//            }else if (!ObjectUtils.isEmpty(command.getTeamId())){
//                List<Integer> teamIds = new ArrayList<>();
//                teamIds.add(command.getTeamId());
//                list.addAll(userTeamShipMapper.selectList(new LambdaQueryWrapper<UserTeamShip>().in(UserTeamShip::getTeamId, teamIds)).stream().map(UserTeamShip::getUserMerchantId).toList());
//            }
        }
        command.setSysUserIds(list);
        command.setIsRun(0);
        IPage<CustomerWechatInfoVo> customerInfoPage = customerInfoService.customerWechatPageQuery(command);
        return PageResult.success(customerInfoPage.getRecords(), customerInfoPage.getTotal());
    }

    @Operation(summary = "分页查询流失客户列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/customerRunPageQuery")
    public PageResult<CustomerWechatInfoVo> customerRunPageQuery(@Validated @RequestBody CustomerWechatPageDto command) {
        command.setIsSalesmanUser(false);
        List<Long> list = new ArrayList<>();
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
            if (SecurityUtils.X.isBokeMerchantUser()) {
                list.addAll(sysUserMerchantMapper.getUserListByMerchantId(merchantId,SecurityUtils.X.getRoleCodeList(),command.getTeamId()));
            }else if (!SecurityUtils.X.isBokeMerchantUser() && SecurityUtils.X.isBokeTeamUser()){
                List<Integer> teamIds = new ArrayList<>();
                if (ObjectUtils.isEmpty(command.getTeamId())){
                    teamIds = teamService.getTeamListByUserId(userId).stream().map(Team::getId).toList();
                }else {
                    teamIds.add(command.getTeamId());
                }
                list.addAll(userTeamShipMapper.selectList(new LambdaQueryWrapper<UserTeamShip>().in(UserTeamShip::getTeamId, teamIds)).stream().map(UserTeamShip::getUserMerchantId).toList());
            }else {
                list.add(userId);
                command.setIsSalesmanUser(true);
            }
            if (list.size()==0){
                return PageResult.success(null,0);
            }
        }else {
            list.addAll(sysUserMerchantMapper.getUserListByMerchantId(command.getMerchantId(),SecurityUtils.X.getRoleCodeList(),command.getTeamId()));
//            if (!ObjectUtils.isEmpty(command.getMerchantId())){
//
//            }else if (!ObjectUtils.isEmpty(command.getTeamId())){
//                List<Integer> teamIds = new ArrayList<>();
//                teamIds.add(command.getTeamId());
//                list.addAll(userTeamShipMapper.selectList(new LambdaQueryWrapper<UserTeamShip>().in(UserTeamShip::getTeamId, teamIds)).stream().map(UserTeamShip::getUserMerchantId).toList());
//            }
        }
        command.setSysUserIds(list);
        command.setIsRun(1);
        IPage<CustomerWechatInfoVo> customerInfoPage = customerInfoService.customerWechatPageQuery(command);
        return PageResult.success(customerInfoPage.getRecords(), customerInfoPage.getTotal());
    }

    @Operation(summary = "客户详情", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/customerInfoDetail")
    public Result<OrderUserApplyDetailDTO> customerInfoDetail(@RequestParam(value = "customerId",required = false) Long customerId,
                                                              @RequestParam(value ="wechatCustomerId",required = false) Long wechatCustomerId) {
        OrderUserApplyDetailDTO customerInfoPage = customerInfoService.customerInfoDetail(customerId,wechatCustomerId);
        return Result.success(customerInfoPage);
    }

    @Operation(summary = "操作客户信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/operationCustomerInfo")
    @Resubmit
    public Result<Boolean> operationCustomerInfo(@Validated @RequestBody OperationCustomerInfoDto dto) {
        Long userId = SecurityUtils.X.getUser().getUserId();
        dto.setCreaterId(userId);
        return Result.success(customerInfoService.operationCustomerInfo(dto));
    }

    @Operation(summary = "操作企微客户信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/operationWechatCustomerInfo")
    @Resubmit
    public Result<Boolean> operationWechatCustomerInfo(@Validated @RequestBody OperationWechatCustomerInfoDto dto) {
        Long userId = SecurityUtils.X.getUserId();
        dto.setUserId(userId);
        return Result.success(customerInfoService.operationWechatCustomerInfo(dto));
    }

    @Operation(summary = "查询客户信息详情", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/CustomerOperationInfo")
    public Result<CustomerOperationInfoVo> CustomerOperationInfo(@RequestParam(value = "customerId",required = false) Long customerId) {
        return Result.success(customerInfoService.CustomerOperationInfo(customerId));
    }

    @Operation(summary = "新增客户和标记统计", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/newCustomerCount")
    public Result<newCustomerCountVo> newCustomerCount() {
        return Result.success(customerInfoService.newCustomerCount());
    }

    @Operation(summary = "通过系统客户id查看客户操作记录", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/getOperationLogByCustomerId")
    public Result<List<CustomerOperationLog>> getOperationLogByCustomerId(@RequestParam(value = "customerId") Long customerId) {
        return Result.success(customerInfoService.getOperationLogByCustomerId(customerId));
    }

    @Operation(summary = "通过企微客户id查看客户操作记录", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/getOperationLogByWechatCustomerId")
    public Result<List<CustomerOperationLog>> getOperationLogByWechatCustomerId(@RequestParam(value = "wechatCustomerId") Long wechatCustomerId) {
        return Result.success(customerInfoService.getOperationLogByWechatCustomerId(wechatCustomerId));
    }

}
